<template>
	<div class="page-common-layout">
		<div class="page-common-left" style="width:15%;padding: 0">
			<TableClassify :title="classifyTitle" :treeData="classifyData" @select="masterRowClick"
				:replaceFields="{ title: 'name', key: 'uuid' }" :loading="masterConfirmLoading" searchPlaceholder="名称"
				searchFieldName="name"></TableClassify>
		</div>
		<div class="page-common-content">
			<tool-bar @search="fetch" @reset="() => {
				subQueryParam.tableName = '';
				subQueryParam.tableRemarks = '';
				subQueryParam.tableType = '';
				fetch()
			}">
				<template slot="toolBtn" slot-scope="scope">
					<a-button class="cu-btn-primary" icon="plus" @click="openCard()">新建</a-button>
				</template>
				<template slot="toolForm">
					<a-form-item label="表名">
						<a-input v-model="subQueryParam.tableName" placeholder="表名" />
					</a-form-item>
					<a-form-item label="表注释">
						<a-input v-model="subQueryParam.tableRemarks" placeholder="表注释" />
					</a-form-item>
					<a-form-item label="类型">
						<a-input v-model="subQueryParam.tableType" placeholder="类型" />
					</a-form-item>
				</template>
			</tool-bar>
			<div style="height: calc(100% - 145px);">
				<a-spin :spinning="subConfirmLoading">
					<a-table ref="subList" size="small" :columns="subColumns" :data-source="dataSource" rowKey="tableName"
						showPagination="auto" :pagination="pagination" :scroll="scrollXY">
						<span slot="serial" slot-scope="text, record, index">
							{{ index + 1 }}
						</span>
						<span slot="tableName" slot-scope="text, record">
							<a @click="columnsDetail(record)">{{ text }}</a>
						</span>
						<span slot="tableType" slot-scope="text, record">
							<span>{{ text == 'VIEW' ? '数据视图' : '数据表' }}</span>
						</span>
						<span slot="action" slot-scope="text, record">
							<a @click="handleEdit(record)">编辑</a>
							<span class="action-margin"></span>
							<a @click="handleSub(record)" class="action-delete">删除</a>
							<span class="action-margin"></span>
							<a-dropdown>
								<a class="ant-dropdown-link">更多<a-icon type="down" /></a>
								<a-menu slot="overlay">
									<a-menu-item>
										<a @click="columnsDetail(record)">字段详情</a>
									</a-menu-item>
									<a-menu-item>
										<a @click="dataDetail(record)">查看数据</a>
									</a-menu-item>
								</a-menu>
							</a-dropdown>
						</span>
					</a-table>
				</a-spin>
			</div>
			<!-- 数据表 -->
			<sub-form ref="subModal" :visible="subVisible" :loading="subConfirmLoading" :model="subMdl"
				@cancel="handleCancel('table')" @ok="handleOk('table')" />
			<!-- 数据视图 -->
			<viewForm ref="viewModal" :visible="viewVisible" :loading="viewLoading" :model="viewMdl"
				@cancel="handleCancel('view')" @ok="handleOk('view')" />
			<!-- 数据详情 -->
			<dataDetailForm ref="dataDetail" :visible="dataDetailVisible" @close="dataDetailVisible = false" />
			<!-- 字段详情 -->
			<detail ref="detail" :visible="detailVisible" @close="detailVisible = false" />
			<!-- 新增卡片 -->
			<card-selection ref="cardModal" :visible="cardVisible" @click="openPage" :type="cardType"
				@cancel="() => cardVisible = false" />
		</div>
	</div>
</template>

<script>
import { DataGrid, TableClassify } from "@/components";
import { dataGridMixin } from "@/mixins/dataGridMixin";
import subForm from "./edit.vue";
import cardSelection from "./cardSelection.vue";
import detail from "./detail.vue";
import viewForm from "./viewEdit.vue"
import dataDetailForm from './dataDetail.vue'
export default {
	mixins: [dataGridMixin],
	components: {
		subForm,
		detail,
		viewForm,
		DataGrid,
		TableClassify,
		cardSelection,
		dataDetailForm
	},
	data() {
		return {
			masterColumns: [{
				title: '名称',
				dataIndex: 'name'
			}],
			subColumns: [{
				title: '序号',
				dataIndex: 'serial',
				ellipsis: true,
				width: 50,
				scopedSlots: {
					customRender: "serial"
				},
			}, {
				title: '表名',
				dataIndex: 'tableName',
				scopedSlots: {
					customRender: "tableName"
				},
			},
			{
				title: '表注释',
				dataIndex: 'tableRemarks',
				ellipsis: true,
				scopedSlots: {
					customRender: "tableRemarks"
				},
			},
			{
				title: '类型',
				dataIndex: 'tableType',
				width: 100,
				scopedSlots: {
					customRender: "tableType"
				},
			},
			{
				title: "操作",
				dataIndex: "action",
				width: 160,
				scopedSlots: {
					customRender: "action"
				},
			}],
			cardType: '',
			cardVisible: false,
			masterVisible: false,
			subVisible: false,
			viewVisible: false,
			detailVisible: false,
			dataDetailVisible: false,
			masterConfirmLoading: false,
			subConfirmLoading: false,
			viewLoading: false,
			masterMdl: null,
			subMdl: null,
			viewMdl: null,
			// 查询参数
			masterQueryParam: {},
			subQueryParam: {},
			url: {
				getPageSet: "/system/sysDatabaseConnection/getPageSet",
				subList: "/system/sysDatabaseConnection/getTable",
				deleteBatch: "/system/sysDatabaseConnection/dropTableOrDeleteTableData",
				deleteBatchView: "/system/sysDatabaseConnection/dropView",
			},
			// innerUrl: '/system/sysDatabaseConnection/getColumn', //获取表字段数据地址
			innerUrl: '/system/sysDatabaseConnection/detail',
			viewUrl: '/system/sysDatabaseConnection/modifyView',
			innerData: [], //表字段数据列表
			selectedRowKeys: [],
			pagination: {
				pageSize: 20,
				showSizeChanger: true,
				showQuickJumper: true,
				hideOnSinglePage: false,
				onShowSizeChange: (current, pageSize) =>
					this.onShowSizeChange(current, pageSize),
			},
			pageClientHeight: 0,
			dataSource: [],
			masterConfirmLoading: false,
			classifyData: [],
			classifyTitle: '数据库',
			myicon: 'global',
			isEdit: false, //判断新增or编辑
		};
	},
	computed: {
		rowSelection() {
			return {
				selectedRowKeys: this.selectedRowKeys
			};
		},
		// 表格竖向滚动条设置  这里是根据每页数据条数大于等于20的时候出现滚动条
		scrollXY() {
			let height = "";
			height = this.pageClientHeight - 200;
			const tdHeight = this.dataSource?.length * 40 ?? 0;
			return this.dataSource?.length >= 20 || height < tdHeight
				? { y: height }
				: {};
		},
	},
	mounted() {
		this.resizeHandler();
		this.getClassifyData()
	},
	created() {
		this.$post(this.url.subList, { uuid: '0DD9F4D5DFB546EEBE12E027DC43EB9B' }).then((res) => {
			const pager = {
				...this.pagination,
			};
			pager.total = res.length;
			this.dataSource = res;
			this.pagination = pager;
			this.subQueryParam.uuid = '0DD9F4D5DFB546EEBE12E027DC43EB9B'
		}
		);
	},
	methods: {
		//新增卡片
		openPage(key) {
			if (key === 'table') {
				this.handleAdd('table')
			} else {
				this.handleAdd('view')
			}
			this.cardVisible = false
			this.formType = key
			this.isEdit = false
		},
		//判断用户是否点击了左侧数据库
		openCard() {
			if (!this.subQueryParam.uuid) {
				this.$message.warn(this.$ct("Select the database to be operated on the left first", "请先选中左侧需要操作的数据库"), 1.5);
			} else {
				this.cardVisible = true
			}
		},
		//获取分类数据
		getClassifyData() {
			this.masterConfirmLoading = true
			this.$post(this.url.getPageSet, { pageNo: 1, pageSize: 20 }).then(res => {
				if (res) {
					this.classifyData = res.rows
					this.masterConfirmLoading = false
				}
			})
		},
		masterRowClick(e) {
			this.subQueryParam.uuid = e[0];
			this.fetch();
		},
		resizeHandler() {
			// 获取页面内容的高度
			this.pageClientHeight = document.getElementsByClassName(
				"page-common-content"
			)[0]?.clientHeight;
		},
		//新增表or视图
		handleAdd(type) {
			if (type === 'table') {
				this.$refs.subModal.title = '新建数据表'
				this.subVisible = true
				this.$refs.subModal.add();
			} else if (type === 'view') {
				this.$refs.viewModal.title = '新建数据视图'
				this.viewVisible = true
			}
			this.isEdit = false;
		},
		//字段详情
		columnsDetail(e) {
			this.detailVisible = true;
			this.$refs.detail.queryParam = {
				tableName: e.tableName,
				uuid: this.subQueryParam.uuid
			}
		},
		//数据详情
		dataDetail(e) {
			this.dataDetailVisible = true;
			this.$refs.dataDetail.queryParam = {
				tableName: e.tableName,
				uuid: this.subQueryParam.uuid
			}
		},
		//分页
		onShowSizeChange(current, pageSize) {
			const pager = { ...this.pagination }
			pager.pageSize = pageSize
			this.pagination = pager
			if (this.queryParam) {
				if (this.queryParam.rows || this.queryParam.page) {
					this.fetch({
						rows: pageSize,
						page: current
					})
				} else {
					this.fetch({
						pageSize: pageSize,
						pageNo: current
					})
				}
				this.isNew = false
			}
		},
		//查询
		fetch() {
			this.subConfirmLoading = true
			this.$post(this.url.subList, this.subQueryParam).then((res) => {
				if (res.statusCode !== 300) {
					const pager = {
						...this.pagination,
					};
					pager.total = res.length;
					this.dataSource = res;
					this.pagination = pager;
				} else {
					this.$message.error(res.message ? res.message : '获取数据库数据失败，请检查是否连接成功!');
					this.dataSource = [];
				}
				this.subConfirmLoading = false
			}
			);
		},
		//编辑
		handleEdit(record) {
			if (record.tableType === 'TABLE') {
				this.$refs.subModal.title = '编辑数据表'
				this.$post(this.innerUrl, {
					tableName: record.tableName,
					uuid: this.subQueryParam.uuid
				}).then((res) => {
					//给当前表字段数据赋值
					this.$set(this.innerData, record.tableName, res)
					//给表单数据赋值
					let columsData = this.innerData[record.tableName]
					//对象转数组
					let keys = Object.keys(columsData)
					keys.pop()
					//传回的字符串转布尔
					let values = keys.map(key => columsData[key])
					values = values.map((item) => ({
						...item,
						fieldAllowNull: item.fieldAllowNull === "true",
						fieldPrimaryKey: item.fieldPrimaryKey === "true"
					}))
					this.subMdl = {
						columsData: values,
						uuid: this.subQueryParam.uuid,
						...record
					}
					//显示弹窗
					this.subVisible = true
					this.$refs.subModal.edit(this.subMdl);
				})
			} else {
				this.$refs.viewModal.title = '编辑数据视图'
				this.$post(this.viewUrl, {
					viewName: record.tableName,
					dbConUuid: this.subQueryParam.uuid
				}).then((res) => {
					this.viewMdl = {
						columsData: res.data,
						uuid: this.subQueryParam.uuid,
					}
					this.viewVisible = true
				})
			}

			this.isEdit = true;
		},
		//确定
		handleOk(type) {
			const that = this;
			//判断是新增数据表or数据视图
			//表
			if (type === 'table') {
				that.$refs.subModal.form.validateFields((errors, values) => {
					if (!errors) {
						//判断新增or编辑
						//新增
						if (this.isEdit === false) {
							that.$post("/system/sysDatabaseConnection/createTable", {
								tableName: values.tableName,
								tableRemarks: values.tableRemarks,
								dbConUuid: that.subQueryParam.uuid,
								tableFieldList: JSON.stringify(that.$refs.subModal.data)
							}).then((res) => {
								if (res.statusCode === 200) {
									that.subMdl = {}
									that.$message.success(res.message || that.$ct("operationSucceeded", "操作成功"), 1.5);
									that.subVisible = false;
									this.innerData = []
									this.fetch();
								} else {
									that.$message.error(res.message || that.$ct("operationFailed", "操作失败"), 1.5);
								}
							})
							//编辑
						} else {
							that.$post("/system/sysDatabaseConnection/modifyTable", {
								tableName: values.tableName,
								tableRemarks: values.tableRemarks,
								oldTableName: values.oldTableName,
								dbConUuid: that.subQueryParam.uuid,
								tableFieldList: JSON.stringify(that.$refs.subModal.data)
							}).then((res) => {
								if (res.statusCode === 200) {
									that.subMdl = {}
									that.$message.success(res.message || that.$ct("operationSucceeded", "操作成功"), 1.5);
									that.subVisible = false;
									this.innerData = []
									this.fetch();
								} else {
									that.$message.error(res.message || that.$ct("operationFailed", "操作失败"), 1.5);
								}
							})
						}
					}
				})
				//视图
			} else if (type === 'view') {
				that.$refs.viewModal.form.validateFields((errors, values) => {
					if (!errors) {
						that.$post("/system/sysDatabaseConnection/saveView", {
							sql: values.sql,
							uuid: that.subQueryParam.uuid,
						}).then((res) => {
							if (res.statusCode === 200) {
								that.$message.success(res.message || that.$ct("operationSucceeded", "操作成功"), 1.5);
								that.viewVisible = false;
								this.fetch()
							} else {
								that.$message.error(res.message || that.$ct("operationFailed", "操作失败"), 1.5);
							}
						})
					}
				})
			}

		},
		//取消
		handleCancel(type) {
			if (type === 'table') {
				this.subVisible = false
				this.innerData = []
				this.subMdl = {}
			} else if (type === 'view') {
				this.viewVisible = false
				this.viewMdl = {}
			}
		},
		//删除
		handleSub(record) {
			const that = this
			let uuids = that.subQueryParam.uuid
			let value = {
				uuid: uuids,
				type: 'drop',
				tableName: record.tableName
			}
			that.$confirm({
				title: that.$ct("tips", "提示"),
				content: that.$ct("deleteConfirmationPrompt", "确定删除该数据吗？删除之后不可恢复！"),
				okText: that.$ct("confirm", "确定"),
				cancelText: that.$ct("cancel", "取消"),
				closable: true,
				icon: () => that.$createElement('a-icon', {
					props: {
						key: 'warning',
						type: 'exclamation-circle',
						twoToneColor: '#faad14'
					}
				}),
				onOk() {
					// 在这里调用删除接口
					if (record.tableType === 'TABLE') {
						//删除表单
						that.$post(that.url.deleteBatch, value).then((res) => {
							if (res.statusCode === 200 || res === 0) {
								that.$message.success(res.message, 1.5)
								if (that.fetch) {
									that.fetch(that.queryParam)
									that.innerData = []
								} else {
									that.$refs.subList.refresh()
								}
							} else {
								that.$message.error(res.message, 1.5)
							}
						})
					} else if (record.tableType === 'VIEW') {
						//删除视图
						that.$post(that.url.deleteBatchView, value).then((res) => {
							if (res.statusCode === 200 || res === 0) {
								that.$message.success(res.message, 1.5)
								if (that.fetch) {
									that.fetch(that.queryParam)
								} else {
									that.$refs.subList.refresh()
								}
							} else {
								that.$message.error(res.message, 1.5)
							}
						})
					}
				},
				onCancel() { }
			})
		},
		//监听resize
		initResizeEvent() {
			window.addEventListener("resize", this.resizeHandler, false);
		},
		//移除resize
		destroyResizeEvent() {
			window.removeEventListener("resize", this.resizeHandler);
		},
	},
};
</script>

<style lang="less" scoped>
.ant-table-small tr.ant-table-expanded-row td>.ant-table-wrapper {
	margin: 0px -8px 0px !important;
}

/deep/ tr.ant-table-expanded-row {
	background: #ffffff !important;
}
</style>

